﻿#include "dialog_mc_update.h"
#include "ui_dialog_mc_update.h"
#include <QFileDialog>
#include <QDebug>

Dialog_mc_update::Dialog_mc_update(UsbBox *box, int addr, QWidget *parent) :
    QDialog(parent),
    ui (new Ui::Dialog_mc_update),
    box (box),
    address(addr)
{
    ui->setupUi(this);

    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); //去掉右上角的？号
    if (addr == 0) {
        this->setWindowTitle(QString::fromUtf8("通信盒子升级"));
    }else {
        this->setWindowTitle(QString::fromUtf8("控制器升级"));
    }
    QPalette pe;
    pe.setColor(QPalette::WindowText, Qt::black);
    this->ui->UpdateS_Lable->setPalette(pe);
    connect(box, &UsbBox::UpdateNotifySignal, this, &Dialog_mc_update::onProgressCallback);
}

Dialog_mc_update::~Dialog_mc_update(){
    qDebug() << "~Dialog_mc_update";
    disconnect(box, &UsbBox::UpdateNotifySignal, this, &Dialog_mc_update::onProgressCallback);
    delete ui;
}

void Dialog_mc_update::on_pushButton_3_clicked()
{
    QString version;
    qDebug() << "Can addr = " << address;

    if (box->GetVersion(version, address)){
        this->ui->UpdateS_Lable->setText("获取版本成功");
        QPalette pe;
        pe.setColor(QPalette::WindowText, Qt::black);
        this->ui->UpdateS_Lable->setPalette(pe);
    }else {
        this->ui->UpdateS_Lable->setText("获取版本失败");
        QPalette pe;
        pe.setColor(QPalette::WindowText, Qt::red);
        this->ui->UpdateS_Lable->setPalette(pe);
    }
    ui->lineEdit_3->setText(version);
}

void Dialog_mc_update::onProgressCallback(QString s, int percent) {
    this->ui->UpdateS_Lable->setText(s);
    QPalette pe;
    if (percent >= 0) {
        this->ui->progressBar->setValue(percent);
        pe.setColor(QPalette::WindowText, Qt::black);
    }else {
        pe.setColor(QPalette::WindowText, Qt::red);
    }
    this->ui->UpdateS_Lable->setPalette(pe);
}

void Dialog_mc_update::on_pushButton_clicked()
{
    QFileDialog *fileDia = new QFileDialog(this);
    fileDia->setWindowTitle(QString::fromUtf8("选择文件"));
    fileDia->setDirectory("./");
    fileDia->setNameFilter(tr("File(*.bin)"));
    fileDia->setFileMode(QFileDialog::ExistingFile);
    fileDia->setViewMode(QFileDialog::List);
    if (fileDia->exec()){
        file_name = fileDia->selectedFiles().at(0);
        qDebug() << "File: " << file_name;
        this->ui->lineEdit->setText(file_name);
    }
}


void Dialog_mc_update::on_pushButton_2_clicked()
{
    //do upgrade
    qDebug() << "Can addr = " << address;
    box->UpdateFwFromFile(file_name, address);
}

